package com.zjitc.service.impl;

import com.mysql.jdbc.interceptors.SessionAssociationInterceptor;
import com.zjitc.common.ServerResponse;
import com.zjitc.dao.UserDao;
import com.zjitc.model.User;
import com.zjitc.service.UserService;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Aspire on 2018/3/28.
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private UserDao userDao;

  @Override
  public ServerResponse login(String username, String password) {
    if ("".equals(username) || username == null || "".equals(password) || password == null) {
      return ServerResponse.createError("参数错误");
    }

    User user = userDao.login(username, password);
    if (user != null) {
      return ServerResponse.createSuccess(user);
    }

    return ServerResponse.createError("密码错误");
  }

  @Override
  public ServerResponse register(User user) {
    //用户为空
    if (user == null) {
      return ServerResponse.createError("参数错误");
    }
    //校验用户名是否存在
    int rowCount = userDao.checkUsername(user.getUsername());
    if (rowCount > 0) {
      return ServerResponse.createError("用户已存在");
    }
    //校验注册
    int resultCount = userDao.register(user);
    if (resultCount == 0) {
      return ServerResponse.createError("注册失败");
    }
    return ServerResponse.createSuccess("校验成功");
  }

  @Override
  public ServerResponse check_valid(String str, String type) {
    if (type.equals("username")) {
      int count = userDao.checkUsername(str);
      if (count ==1) {
        return ServerResponse.createError("用户已存在");
      }
      return ServerResponse.createSuccess("校验成功");
    }
    if (type.equals("email")) {
      int rcount = userDao.checkEmail(str);
      if (rcount ==1) {
        return ServerResponse.createError("用户已存在");
      }
      return ServerResponse.createSuccess("校验成功");
    }

    return ServerResponse.createSuccess("校验成功");
  }
  @Override
  public ServerResponse get_user_info(HttpSession session) {
    //session.setAttribute("username","admin");
    User user= (User) session.getAttribute("username");
    int count=userDao.checkUsername(user.getUsername());
    if (count==1) {
      return ServerResponse.createSuccess(user);
    }
    return ServerResponse.createError("用户未登录，无法获取当前用户信息");

  }
}